package client;

import java.util.List;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;

public class W1 implements Watcher{
	
	public ZooKeeper zk = null;

	@Override
	public void process(WatchedEvent event) {
		

		System.out.println("进入 process 。。。。。event = " + event);

		try {
			Thread.sleep(200);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		if (event == null) {
			return;
		}

		// 连接状态
		KeeperState keeperState = event.getState();
		// 事件类型
		EventType eventType = event.getType();
		// 受影响的path
		String path = event.getPath();


		if (KeeperState.SyncConnected == keeperState) {
			// 成功连接上ZK服务器
			if (EventType.None == eventType) {
				System.out.println( "成功连接上ZK服务器");
			}
			// 创建节点
			else if (EventType.NodeCreated == eventType) {
				System.out.println( "节点创建");
				try {
					zk.exists("/aa1",	true);
//					zk.getChildren("/aa1",	true);
					Thread.sleep(100);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			// 更新节点
			else if (EventType.NodeDataChanged == eventType) {
				System.out.println( "节点数据更新");
				try {
//					zk.exists("/aa1",	true);
					zk.getChildren("/aa1",	true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			// 更新子节点
			else if (EventType.NodeChildrenChanged == eventType) {
				System.out.println("子节点变更");
				try {
//					zk.exists("/aa1",	true);
					List<String >children = zk.getChildren("/aa1",	true);
					
					System.out.println(children);
					for(String p:children) {
						byte [] b=zk.getData("/aa1/"+p, true, null);
						System.out.println(p+" : "+new String(b));
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			// 删除节点
			else if (EventType.NodeDeleted == eventType) {
				try {
					zk.exists("/aa1",	true);
//					zk.getChildren("/aa1",	true);
				} catch (KeeperException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("节点 " + path + " 被删除");
			} else
				;
		} else if (KeeperState.Disconnected == keeperState) {
			System.out.println("与ZK服务器断开连接");
		} else if (KeeperState.AuthFailed == keeperState) {
			System.out.println("权限检查失败");
		} else if (KeeperState.Expired == keeperState) {
			System.out.println("会话失效");
		} else
			;

		System.out.println("--------------------------------------------");

		
	}

}
